package com.epoint.BookManager.action;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.epoint.BookManager.dao.BookInfoDao;
import com.epoint.BookManager.domain.BookInfo;
import com.epoint.BookManager.service.BookInfoService;

@WebServlet("/bookinfoeditaction")
public class BookInfoEditAction extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    	BookInfoService bookInfoService = new BookInfoService();


    public BookInfoEditAction() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String method = request.getParameter("method");

        if ("editbookinfo".equals(method)) {
        	Map<String, String> result = new HashMap<>();
            String data = request.getParameter("data");
            JSONObject jsonObject = JSONObject.parseObject(data);
    		BookInfo bookInfo = JSON.toJavaObject(jsonObject, BookInfo.class);
    		String bookid = bookInfo.getBookid();
    		String publisher = bookInfo.getPublisher();
    		int booktype = bookInfo.getBooktype();
    		BookInfoDao bookInfoDao = new BookInfoDao();
    		int i = bookInfoDao.updateBookInfo(booktype, publisher, bookid);
    		if(i==1) {
    			result.put("msg", "保存成功");
    		}else {
				result.put("msg", "保存失败");
			}
    		response.getWriter().print(JSONUtils.toJSONString(result));
    		
        }
        else if ("deleteBookInfo".equals(method)) {
        	boolean flag=false;
            String bookId = request.getParameter("id");
            String[] book = bookId.split(",");
            try {
            	for(int i = 0;i<book.length;i++) {
            	flag = 	deleteBookInfo(book[i], response);
            	}
			} catch (SQLException e) {
				e.printStackTrace();
			} 
            Map<String ,String> resultMap = new HashMap<>();
    		if (flag) {
				resultMap.put("msg", "删除成功");
			}else {
				resultMap.put("msg", "删除失败");
			}
    		response.getWriter().print(JSONUtils.toJSONString(resultMap));
        }

    }


    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }



    private boolean deleteBookInfo(String bookId, HttpServletResponse response) throws IOException, SQLException {
    		return bookInfoService.deleteBook(bookId);	
    }


      
//   
//    }
}
